import { useState } from 'react'
import { Form, Input, Button, Card, message, Space, Divider } from 'antd'
import { UserOutlined, LockOutlined, GithubOutlined, GoogleOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { login, oauth2Login } from '../api/auth'
import { useAuthStore } from '../store/authStore'
import './Login.css'

export default function Login() {
  const navigate = useNavigate()
  const { login: setAuth } = useAuthStore()
  const [loading, setLoading] = useState(false)

  const onFinish = async (values: { username: string; password: string }) => {
    setLoading(true)
    try {
      const response = await login(values)
      // 使用后端返回的用户信息，如果没有则使用默认值
      const user = response.user || {
        id: '1',
        username: values.username,
        email: '',
      }
      setAuth(
        response.access_token,
        response.refresh_token,
        user
      )
      message.success('登录成功')
      navigate('/')
    } catch (error: any) {
      message.error(error?.response?.data?.error || '登录失败')
    } finally {
      setLoading(false)
    }
  }

  const handleOAuth2Login = (provider: string) => {
    oauth2Login(provider)
  }

  return (
    <div className="login-container">
      <Card className="login-card" title="API Gateway 管理平台">
        <Form
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              block
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
        <Divider>或</Divider>
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <Button
            icon={<GithubOutlined />}
            block
            onClick={() => handleOAuth2Login('github')}
          >
            使用 GitHub 登录
          </Button>
          <Button
            icon={<GoogleOutlined />}
            block
            onClick={() => handleOAuth2Login('google')}
          >
            使用 Google 登录
          </Button>
        </Space>
      </Card>
    </div>
  )
}


